package cn.anecansaitin.whimsy.client.listener;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.client.registers.ModKeyMappings;
import cn.anecansaitin.whimsy.common.capabilities.battle.IBattleMode;
import cn.anecansaitin.whimsy.common.item.IBattleControllerSupplier;
import cn.anecansaitin.whimsy.common.network.BattleModeSwitchPack;
import cn.anecansaitin.whimsy.common.network.NetworkHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.event.TickEvent;

@Mod.EventBusSubscriber(modid = Whimsy.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT)
public class OnClientTick {
    @SubscribeEvent
    public static void tick(TickEvent.ClientTickEvent event) {
        if (event.phase == TickEvent.Phase.END) {
            boolean needSwitch = false;
            LocalPlayer player = Minecraft.getInstance().player;

            while (ModKeyMappings.BATTLE_MODE.get().consumeClick()) {
                needSwitch = !needSwitch;
            }

            if (needSwitch) {
                IBattleMode battleMode = player.getCapability(IBattleMode.BATTLE_MODE);

                if (battleMode.isInMode()) {
                    battleMode.switchMode(player);
                    NetworkHelper.toServerPlayer(new BattleModeSwitchPack());
                } else if (player.getMainHandItem().getItem() instanceof IBattleControllerSupplier supplier && supplier.canSwitch(player)) {
                    battleMode.setController(supplier.getBattleControllerId());
                    battleMode.switchMode(player);
                    NetworkHelper.toServerPlayer(new BattleModeSwitchPack());
                }
            }
        }
    }
}
